<template>
  <div id="gar-container">
    <h1>垃圾分类识别</h1>
    <!-- 输入表单 -->
    <el-form style="user-select: none;">
      <el-form-item label="输入文本：">
        <el-input v-model="inputText" placeholder="请输入垃圾描述："></el-input>
      </el-form-item>
      <el-form-item label="上传图片：">
        <!-- 手动上传组件 -->
        <el-upload
          :action="actionUrl"
          name="file"
          :auto-upload="true"
          :show-file-list="false"
          :on-success="handleSuccess"
          accept="image/*"
          class="avatar-uploader"
        >
          <img v-if="imageUrl" :src="imageUrl" class="avatar pre_img" />
          <el-icon v-else class="avatar-uploader-icon">
            <Plus />
          </el-icon>
        </el-upload>
      </el-form-item>
      <el-form-item>
        <el-button class="commit_btn" type="primary" @click="handleSubmit">识别</el-button>
      </el-form-item>
    </el-form>
    <!-- 识别结果 -->
    <div class="recognize_content" v-if="identifyStatus">
      <p>识别结果：{{ result.result }}</p>
      <p class="recognize_content_extra">分析：{{ result.extraInfo }}</p>
    </div>
    <!-- 底部文本提示 -->
    <div class="decorative-content" style="user-select: none;">
      <img src="./assets/garIcon.png" />
      <p>垃圾分类有助于保护环境，请正确分类您的垃圾。</p>
    </div>
  </div>
  <!-- 统计组件展示 -->
   <div class="statistical_container">
    <Statistical ref="StatisticalCP"></Statistical>
   </div>
</template>

<script setup>
import { ref } from "vue";
import { ElMessage, ElLoading } from "element-plus";
import { Plus } from '@element-plus/icons-vue';
import axios from "axios";
import Statistical from "./components/Statistical.vue";

// 统计组件
let StatisticalCP = ref(null);

// 用户输入的文本
const inputText = ref("");;
// 图片地址（预览地址）
const imageUrl = ref("");
// 上传图片成功后的参数
const picData = ref({});
// 手动上传地址
const actionUrl = "http://localhost:9090/commons/upload";

// 上传状态
const uploadStatus = ref(false);
// 识别的状态
const identifyStatus = ref(false);

// 识别的结果
const result = ref({});

// 遮罩层
let loadingElement = ref({});

// 上传成功处理
const handleSuccess = (res) => {
  try {
    picData.value = res.data;
    imageUrl.value = res.data.url; // 赋值预览
    ElMessage.success("图片上传成功");
    uploadStatus.value = true;
    console.log("-=-=-=", result.value.url);
    
  } catch (error) {
    ElMessage.error("图片上传失败");
    uploadStatus.value = false;
  }
};

// 移除图片处理器
const handleRemove = (file, fileList) => {
  console.log(file, fileList);
};

// 提交处理器
const handleSubmit = () => {
  if (!inputText.value && !uploadStatus.value) {
    ElMessage.error("请输入文本或上传图片进行识别");
    return;
  }
  // 处理识别逻辑 - 分发执行处理
  if (inputText.value) {
    handleText(inputText.value);
    return 1;
  }
  // 图片处理
  handleImage();

};

// 图片处理执行器
async function handleImage() {
  // 构造条件对象参数
  let paramObj = {
    picName: picData.value.pictureName,
    question: ""
  }

  openFullScreen(); // 打开加载样式

  // 发送请求
  try {
    const res = await axios.post("http://localhost:9090/ai/visualProcess", paramObj);
    // 结果JSON结构：
    //{extraInfo: "图片内容不符合垃圾分类场景，请上传垃圾实物照片。",
    //result: "无法识别",
    //state: false}
    result.value = res.data;
    ElMessage.success("识别成功");

    identifyStatus.value = true; // 标识识别成功
    afterHandleOfSuccess(); // 识别成功后置处理器
  } catch (error) {
    console.error("识别失败", error);
    ElMessage.error("识别失败");
    loadingElement.value.close(); // 关闭加载样式

  }
}

// 文本处理执行器
async function handleText(question) {
  // 构造条件对象参数
  let paramObj = {
    picName: "",
    question: question
  }

  openFullScreen(); // 打开加载样式

  // 发送请求
  try {
    const res = await axios.post("http://localhost:9090/ai/textProcess", paramObj);
    result.value = res.data;
    ElMessage.success("识别成功");

    identifyStatus.value = true; // 标识识别成功
    afterHandleOfSuccess(); // 识别成功后置处理器
  } catch (error) {
    console.error(error);
    ElMessage.error("识别失败");
    loadingElement.value.close(); // 关闭加载样式
  }
}

// 识别成功后置处理器
function afterHandleOfSuccess(){
  loadingElement.value.close(); // 关闭加载样式
  // 清空表单
  // imageUrl.value = "";
  // inputText.value = "";

  console.log("识别的结果", result.value);
  

  // 存储数据
  saveDataToMongoDB();
}

// 将数据存储到MongoDB中
async function saveDataToMongoDB(){
  // 发送请求
  try {
    const res = await axios.post("http://localhost:9090/statistical", result.value);
    console.log("数据存储成功", res.data);

    // 存储成功后，调用子组件中更新函数，实现图表数据更新
    StatisticalCP.value.reGetChartData();
  } catch (error) {
    console.error("数据存储失败", error);
  }
}

// 识别加载中遮罩层控制
const openFullScreen = () => {
  loadingElement.value = ElLoading.service({
    lock: true,
    text: 'Loading',
    background: 'rgba(0, 0, 0, 0.7)',
  })
}

</script>

<style scoped>
::v-deep .el-form-item__label {
  color: white !important;
}

.commit_btn {
  width: 100px;
  height: 40px;
}

.pre_img{
  border-radius: 10px;
}

#gar-container {
  width: 60vw;
  /* height: 80vh; */
  border-radius: 10px;
  padding: 10px;
  margin: 0 auto;
  border: solid #446e80 1px;
  text-align: center;
  background-color: black;
  background-image:
    radial-gradient(white, rgba(255, 255, 255, .2) 2px, transparent 40px),
    radial-gradient(white, rgba(255, 255, 255, .15) 1px, transparent 30px),
    radial-gradient(white, rgba(255, 255, 255, .1) 2px, transparent 40px),
    radial-gradient(rgba(255, 255, 255, .4), rgba(255, 255, 255, .1) 2px, transparent 30px);
  background-size: 550px 550px, 350px 350px, 250px 250px, 150px 150px;
  background-position: 0 0, 40px 60px, 130px 270px, 70px 100px;
  color: white;
}

.decorative-content {
  margin-top: 20px;
}

.decorative-content img {
  width: 100px;
  height: auto;
}

.decorative-content p {
  margin-top: 10px;
  color: #446e80;
}

.el-icon.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 178px;
  height: 178px;
  text-align: center;
}

.avatar-uploader {
  display: block;
}
.avatar-uploader .el-upload {
  border: 1px dashed var(--el-border-color);
  border-radius: 6px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  transition: var(--el-transition-duration-fast);
}
.avatar-uploader .el-upload:hover {
  border-color: var(--el-color-primary);
}
.avatar-uploader-icon {
  width: 178px;
  height: 178px;
  display: flex;
  align-items: center;
  justify-content: center;
  background-color: var(--el-fill-color-light);
}
.avatar {
  width: 178px;
  height: 178px;
  display: block;
  object-fit: contain;
}


.recognize_content{
  color: white;
  font-weight: 600;
  font-size: 17px;
  width: 80%;
  margin: 0 auto;
  background: rgba(255,255,255, 0.3);
  padding: 5px 20px;
  border-radius: 10px;
}

.recognize_content_extra{
  font-size: 15px;
}

.statistical_container{
  width: 60vw;
  margin: 0 auto;
  margin-top: 20px;
  border-radius: 10px;
  padding: 10px;
  border: solid #446e80 1px;
}
</style>
